#include <QPushButton>
#include <QVBoxLayout>
#include <data_display/totpwindow.h>

namespace data_display {

TOTPWindow::TOTPWindow(utils::ClipboardWatcher &clipboard_watcher, QWidget *parent): QDialog(parent),
		_clipboard_wather(clipboard_watcher), popup(nullptr) {

	setWindowTitle("Временные пароли");
	totpListWindow = new TOTPListWidget(_clipboard_wather, this);
	connect(totpListWindow, SIGNAL(PasswordCopied()), this, SLOT(openPopupWindow()));

	auto *openConfigButton = new QPushButton("Добавить новый одноразовый пароль", this);
	connect(openConfigButton, &QPushButton::clicked, this, &TOTPWindow::addTOTP);

	setLayout(new QVBoxLayout(this));
	layout()->addWidget(totpListWindow);
	layout()->addWidget(openConfigButton);
}

TOTPWindow::TOTPWindow(const std::vector<totp::TOTP> &totps, utils::ClipboardWatcher &clipboard_watcher,
		QWidget *parent) : QDialog(parent), _clipboard_wather(clipboard_watcher), popup(nullptr) {

	setWindowTitle("Временные пароли");
	totpListWindow = new TOTPListWidget(_clipboard_wather, this);
	connect(totpListWindow, SIGNAL(PasswordCopied()), this, SLOT(openPopupWindow()));
	connect(totpListWindow, &TOTPListWidget::totpDeleted, this, &TOTPWindow::onTotpDeleted);

	auto *openConfigButton = new QPushButton("Добавить новый одноразовый пароль", this);
	connect(openConfigButton, &QPushButton::clicked, this, &TOTPWindow::addTOTP);

	setLayout(new QVBoxLayout(this));
	layout()->addWidget(totpListWindow);
	layout()->addWidget(openConfigButton);
	fillTotpListWindow(totps);
}

void TOTPWindow::addTOTP() {
	auto *configWindow = new TOTPConfigWindow(this);
	configWindow->setModal(true);
	connect(configWindow, &TOTPConfigWindow::configSaved, this, &TOTPWindow::addTOTPToList);
	configWindow->show();
}

void TOTPWindow::addTOTPToList(const QString& label, const Botan::SymmetricKey& key, const QString& algorithm,
	int digits, int period) {
	if (!totpListWindow)
		totpListWindow = new TOTPListWidget(_clipboard_wather,this);

	totp::TOTP totp(label, key, algorithm, digits, period);
	totpListWindow->addTOTP(totp);
	emit addedTotp(totp);
}

void TOTPWindow::fillTotpListWindow(const std::vector<totp::TOTP>& totps) {
	for(const auto& totp: totps)
		totpListWindow->addTOTP(totp);

}
void TOTPWindow::onTotpDeleted(const totp::TOTP& totp) {
	emit deleteTotp(totp); // Передаем сигнал на удаление в основное приложение или другую часть программы
}
void TOTPWindow::openPopupWindow() {
	popup = new utils::PopUp(QWidget::geometry());
	popup->setPopupText("Пароль скопирован в буфер обмена");
	popup->show();
}
}
